from django.http import HttpRequest, HttpResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response

from cou_ord.serializers import OrderSerializer, SturecoedSerializer
from education.models import Order, User, Sturecord


@api_view(('GET', ))
def show_order(request: HttpRequest) -> HttpResponse:
    """获取指定用户所有订单"""
    userid = int(request.GET.get('userid', ''))
    username = User.objects.only('username').get(userid=userid)
    queryset = Order.objects.filter(user=userid).filter(is_deleted=0)
    order_seri = OrderSerializer(queryset, many=True)
    return Response({'username': username.username, 'order': order_seri.data})


@api_view(('GET', ))
def show_consumption(request: HttpRequest) -> HttpResponse:
    """查询消费记录"""
    userid = int(request.GET.get('userid', ''))
    username = User.objects.only('username').get(userid=userid)
    queryset = Order.objects.filter(is_pay=1).filter(user=userid)
    consumption = []
    for order in queryset:
        if order.is_pay:
            consumption.append(order.price)
    return Response({'username': username.username, 'consumption': consumption})


@api_view(('GET', ))
def delete_order(request: HttpRequest) -> HttpResponse:
    """删除指定订单"""
    orderid = int(request.GET.get('orderid', ''))
    order = Order.objects.get(orderid=orderid)
    order.is_deleted = 1
    order.save()
    return Response({'code': 10000, 'message': '删除成功'})


@api_view(('GET', ))
def show_balance(request: HttpRequest) -> HttpResponse:
    """获取指定用户余额信息"""
    userid= int(request.GET.get('userid', ''))
    user = User.objects.get(userid=userid)
    return Response({'username': user.username, 'balance': user.balance})


@api_view(('POST', 'GET'))
def recharge(request: HttpRequest) -> HttpResponse:
    """充值"""
    userid = int(request.GET.get('userid', ''))
    money = int(request.data.get('money', ''))
    user = User.objects.get(userid=userid)
    user.balance += money
    user.save()
    return Response({'code': 20000, 'message': '充值成功'})


@api_view(('GET', ))
def show_sturecoed(request: HttpRequest) -> HttpResponse:
    """获取指定用户的学习记录"""
    userid = int(request.GET.get('userid', ''))
    username = User.objects.only('username').get(userid=userid)
    queryset = Sturecord.objects.filter(userid=userid)
    learned = []
    learning = []
    for sturecoed in queryset:
        if sturecoed.is_completed:
            learned.append(SturecoedSerializer(sturecoed).data)
        else:
            learning.append(SturecoedSerializer(sturecoed).data)
    return Response({'username': username.username, 'learned': learned, 'learning': learning})




